# Copyright 2021 Huawei Technologies Co., Ltd.All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ==============================================================================
"""Vocabulary of the model."""
from typing import List, Tuple


class Vocabulary:
    """Vocabulary util."""

    def __init__(self):
        self.symbols = []
        self.frequency = []
        self.mapping = {}

    @property
    def size(self):
        return len(self.symbols)

    def __contains__(self, symbol):
        return symbol in self.mapping

    def __getitem__(self, idx):
        if 0 <= idx < self.size:
            return self.symbols[idx]
        return None

    def __len__(self):
        return self.size

    def index(self, symbol: str):
        """
        Return id according to symbol.

        Args:
            symbol (str): Symbol.

        Returns:
            int, id.
        """
        idx = self.mapping.get(symbol)
        if idx is None:
            return None
        return idx

    def add_symbol(self, symbol, times=1):
        """
        Add symbol to dict.

        Args:
            symbol (str): Symbol.
            times (int): Frequency.

        Returns:
            int, token id.
        """
        if symbol in self.mapping:
            idx = self.mapping[symbol]
            self.frequency[idx] = self.frequency[idx] + times
            return idx

        idx = len(self.symbols)
        self.mapping[symbol] = idx
        self.symbols.append(symbol)
        self.frequency.append(times)
        return idx

    @classmethod
    def load_from_text(cls, zh_vocab_path):
        """Load dict from text which is in format of [word, freq]."""
        _dict = cls()
        with open(zh_vocab_path, "r", encoding="utf-8") as f:
            for _, line in enumerate(f):
                line = line.strip()
                if line is None:
                    continue
                try:
                    word = line
                    _dict.add_symbol(word)
                except ValueError:
                    continue
        return _dict

    def tokenize(self, text: str) -> Tuple[List[int], List[int]]:
        """Tokenize the text and convert it to ids."""
        text = ["[CLS]"] + list(text) + ["[SEP]"]
        attn_mask = [1] * len(text)
        return self.convert_tokens_to_ids(text), attn_mask

    def convert_tokens_to_ids(self, tokens):
        """Convert tokens to ids."""
        return [self.index(w) for w in tokens]

    def convert_ids_to_tokens(self, ids):
        """Convert ids to tokens."""
        return [self[i] for i in ids]
